package com.xk857.simpleeffect.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.gson.reflect.TypeToken;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Business;
import com.xk857.simpleeffect.domain.param.AddBusinessParam;
import com.xk857.simpleeffect.domain.vo.ProjectSimpleVO;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.CalendarUtils;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;

public class AddTodoActivity extends AppCompatActivity {

    private TextView leftDateWeekText;
    private TextView leftDateText;
    private TextView rightDateWeekText;
    private TextView rightDateText;

    private AddBusinessParam addBusiness;
    private TextView remindText;
    private RadioGroup radioGroup;


    private static final SimpleDateFormat canalSdf = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
    private EditText titleEdit;
    private EditText remarkEdit;
    private LinearLayout projectLayout;
    private TextView projectText;

    private List<ProjectSimpleVO> projectList;
    private TextView iconRightImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_add_todo);
        initView();
        initData();
    }

    private void initData() {
        // 初始化开始时间和结束时间都是今天
        addBusiness = new AddBusinessParam(0 + "", Calendar.getInstance(), Calendar.getInstance());
        leftDateText.setText(DateUtil.format(new Date(), "MM月dd日"));
        leftDateWeekText.setText("今天");
        rightDateText.setText(DateUtil.format(new Date(), "MM月dd日"));
        rightDateWeekText.setText("今天");

        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton radioButton = group.findViewById(checkedId);
            int i = group.indexOfChild(radioButton);
            addBusiness.setIcon(String.valueOf(i));
        });

        // 获取所有项目数据
        Type type = new TypeToken<Result<List<ProjectSimpleVO>>>() {}.getType();
        OkHttpUtils.getInstance().get(this, RequestEnum.GET_ME_PROJECT, type, false, (Consumer<List<ProjectSimpleVO>>) projectList -> this.projectList = projectList);
    }

    private void initView() {
        TitleBar titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftClickListener(v -> finish());
        leftDateWeekText = findViewById(R.id.left_date_week_text);
        leftDateText = findViewById(R.id.left_date_text);
        rightDateWeekText = findViewById(R.id.right_date_week_text);
        rightDateText = findViewById(R.id.right_date_text);

        leftDateWeekText.setOnClickListener(v -> chooseLeftData());
        leftDateText.setOnClickListener(v -> chooseLeftData());
        rightDateWeekText.setOnClickListener(v -> chooseRightData());
        rightDateText.setOnClickListener(v -> chooseRightData());

        LinearLayout remindLayout = findViewById(R.id.time_layout);
        remindLayout.setOnClickListener(v -> setRemindDate());

        remindText = findViewById(R.id.remind_text);
        radioGroup = findViewById(R.id.radio_group);
        Button addButton = findViewById(R.id.add_btn);
        titleEdit = findViewById(R.id.title_edit);
        remarkEdit = findViewById(R.id.remark_edit);


        addButton.setOnClickListener(v -> {
            if (addBusiness.getStartDate().compareTo(addBusiness.getEndDate()) > 0) {
                new MaterialDialog.Builder(this).iconRes(R.drawable.icon_info).title(R.string.hint).content("结束日期不能小于开始日期").positiveText(R.string.yes).show();
                return;
            }
            if (StrUtil.hasBlank(titleEdit.getText().toString())) {
                new MaterialDialog.Builder(this).iconRes(R.drawable.icon_info).title(R.string.hint).content("待办名称不可为空").positiveText(R.string.yes).show();
                return;
            }
            addBusiness.setTitle(titleEdit.getText().toString());
            addBusiness.setRemark(remarkEdit.getText().toString());
            addBusiness.setStartTime(canalSdf.format(addBusiness.getStartDate().getTime()));
            addBusiness.setEndTime(canalSdf.format(addBusiness.getEndDate().getTime()));
            Type type = new TypeToken<Result<Business>>() {}.getType();
            OkHttpUtils.getInstance().post(AddTodoActivity.this, RequestEnum.ADD_BUSINESS, type, addBusiness, true, (Consumer<Business>) business -> {
                if (business.getCreateTime() != null) {
                    runOnUiThread(() ->
                            new MaterialDialog.Builder(this).iconRes(R.drawable.icon_success).title(R.string.success).content("待办任务添加成功").positiveText(R.string.yes).onPositive((dialog, which) -> {
                                finish();
                            }).show()
                    );
                }
            });
        });

        projectLayout = findViewById(R.id.project_layout);
        projectText = findViewById(R.id.project_text);


        projectLayout.setOnClickListener(view -> {
            if (projectList == null || projectList.size() == 0) {
                new MaterialDialog.Builder(this).iconRes(R.drawable.icon_info).title(R.string.info).content("您还没有创建项目，请在首页->底部导航栏->项目进行创建").positiveText("现在创建").negativeText("取消")
                        .onPositive((dialog, which) -> startActivity(new Intent(this, AddProjectActivity.class))).show();
            } else {
                //计算默认选中的是第几个，如果找不到则为0
                int defaultSelect = projectList.stream().filter(project -> project.getId().equals(addBusiness.getProjectId())).findFirst().map(projectList::indexOf).orElse(0);
                OptionsPickerView<String> pvOptions = new OptionsPickerBuilder(this, (v, options1, options2, options3) -> {
                    projectText.setText(projectList.get(options1).getName());
                    addBusiness.setProjectId(projectList.get(options1).getId());
                    return false;
                }).setTitleText("选中项目").setSelectOptions(defaultSelect).build(); // 标题、默认选中
                pvOptions.setPicker(projectList.stream().map(ProjectSimpleVO::getName).collect(Collectors.toList()));// 选项数据
                pvOptions.show();
            }
        });
        iconRightImg = findViewById(R.id.icon_right_img);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    /**
     * 弹出日期时间选择框，用户输入提醒时间
     */
    private void setRemindDate() {
        new CardDatePickerDialog.Builder(this).setTitle("设置提醒时间")
                .setMinTime(System.currentTimeMillis() + 60000) // 设置最短提醒时间在1分钟后
                .setMaxTime(System.currentTimeMillis() + (6 * 30 * 24 * 60 * 60 * 1000L)) // 最大只能选择6个月内的时间
                .showBackNow(false) //不显示回到此刻
                .showFocusDateInfo(true) // 显示选中日期信息
                .setThemeColor(getColor(R.color.main)) //设置主题色
                .setBackGroundModel(CardDatePickerDialog.STACK) // 设置顶部圆角
                .setPickerLayout(R.layout.layout_date_picker_segmentation) // 自定义选择格式布局文件
                .setLabelText("", "", "", "点", "分", "")
                .setOnChoose("确定", aLong -> {
                    Instant instant = Instant.ofEpochMilli(aLong);
                    LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                    List<Integer> remindTimeList = new ArrayList<>(6);
                    remindTimeList.add(date.getYear());
                    remindTimeList.add(date.getMonthValue());
                    remindTimeList.add(date.getDayOfMonth());
                    remindTimeList.add(date.getHour());
                    remindTimeList.add(date.getMinute());
                    remindTimeList.add(date.getSecond());
                    addBusiness.setRemindTime(remindTimeList);
                    if (date.getYear() == LocalDateTime.now().getYear()) {
                        remindText.setText(LocalDateTimeUtil.format(date, "MM月dd日 HH:mm"));
                    } else {
                        remindText.setText(LocalDateTimeUtil.format(date, DatePattern.NORM_DATETIME_MINUTE_PATTERN));
                    }
                    return null;
                }).setOnCancel("不提醒", () -> {
                    addBusiness.setRemindTime(null);
                    remindText.setText(R.string.no_remind);
                    return null;
                }).build().show();
    }

    private void chooseLeftData() {
        showDatePickerDialog(AddTodoActivity.this, 0, leftDateText, leftDateWeekText, addBusiness.getStartDate());
    }

    private void chooseRightData() {
        showDatePickerDialog(AddTodoActivity.this, 1, rightDateText, rightDateWeekText, addBusiness.getEndDate());
    }

    /**
     * 显示系统日期框
     *
     * @param context  环境上下文
     * @param weekText 上侧显示周几的
     * @param dataText 具体日期
     * @param calendar 日历类
     * @param m        0开始 1结束时间
     */
    public void showDatePickerDialog(Context context, int m, final TextView dataText, final TextView weekText, Calendar calendar) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(context, com.xuexiang.xui.R.style.XUITheme_AlertDialog, (view, year, month, day) -> {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(year, month, day);
            dataText.setText(String.format(Locale.getDefault(), "%d月%d日", (month + 1), day));
            weekText.setText(CalendarUtils.getWeek(calendar1));
            if (m == 0) {
                if (calendar1.compareTo(addBusiness.getEndDate()) > 0) {
                    XToast.normal(AddTodoActivity.this, R.string.start_lg_end).show();
                }
                addBusiness.setStartDate(calendar1);
            } else {
                if (calendar1.compareTo(addBusiness.getStartDate()) < 0) {
                    XToast.normal(AddTodoActivity.this, R.string.end_ge_start).show();
                }
                addBusiness.setEndDate(calendar1);
            }
            if (addBusiness.getStartDate()!=null && addBusiness.getEndDate() != null) {
                long differenceInMillis = Math.abs(addBusiness.getEndDate().getTimeInMillis() - addBusiness.getStartDate().getTimeInMillis());
                int differenceInDays = (int) (differenceInMillis / (24 * 60 * 60 * 1000));
                if (differenceInDays == 0) {
                    iconRightImg.setText("24小时");
                }else {
                    iconRightImg.setText(String.format(Locale.CHINA, "%d天", differenceInDays+1));
                }
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }
}